{**
Abstract: Reading and writing settings from INI file
Author:  Prof1983 prof1983@yandex.ru
Created: 24.03.2008
LastMod: 20.02.2009
}
unit AIniSettings;

interface

uses
  Classes, IniFiles, SysUtils,
  ABase, ABaseIntf, ASettings;

type
  TIniSettings = class(TAbstractSettings)
  private
    FIniFile: TIniFile;
  public
    procedure Close();
    function DeleteKey(const Section, Name: AString): ABoolean; override;
    function DeleteSection(const Section: AString): ABoolean; override;
    procedure OpenIniFile(const FileName: AString);
    function ReadSection(const Section: AString; Strings: IAStrings): ABoolean; override;
    function ReadString(const Section, Name, DefValue: AString): AString; override;
    function WriteString(const Section, Name, Value: AString): ABoolean; override;
  end;

implementation

{ TIniSettings }

procedure TIniSettings.Close();
begin
  if Assigned(FIniFile) then
  try
    FIniFile.Free();
  finally
    FIniFile := nil;
  end;
end;

function TIniSettings.DeleteKey(const Section, Name: AString): ABoolean;
begin
  Result := False;
  if Assigned(FIniFile) then
  try
    FIniFile.DeleteKey(Section, Name);
    Result := True;
  except
  end;
end;

function TIniSettings.DeleteSection(const Section: AString): ABoolean;
begin
  Result := False;
  if Assigned(FIniFile) then
  try
    FIniFile.EraseSection(Section);
    Result := True;
  except
  end;
end;

procedure TIniSettings.OpenIniFile(const FileName: AString);
begin
  Close();
  try
    FIniFile := TIniFile.Create(FileName);
  except
    FIniFile := nil;
  end;
end;

function TIniSettings.ReadSection(const Section: AString; Strings: IAStrings): ABoolean;
var
  //Names: TStringList;
  Values: TStringList;
  I: Integer;
begin
  Result := Assigned(FIniFile);
  if Result then
  begin
    //Names := TStringList.Create();
    Values := TStringList.Create();
    try
      //FIniFile.ReadSection(Section, Names);
      FIniFile.ReadSectionValues(Section, Values);
      for I := 0 to Values.Count - 1 do
        Strings.Add(Values.Strings[I]);
        //Strings.Add(Names.Strings[I]+'='+Values.Strings[I]);
    finally
      //Names.Free();
      Values.Free();
    end;
  end;
end;

function TIniSettings.ReadString(const Section, Name, DefValue: AString): AString;
begin
  if Assigned(FIniFile) then
    Result := FIniFile.ReadString(Section, Name, DefValue)
  else
    Result := DefValue;
end;

function TIniSettings.WriteString(const Section, Name, Value: AString): ABoolean;
begin
  Result := Assigned(FIniFile);
  if Result then
    FIniFile.WriteString(Section, Name, Value);
end;

end.
